﻿using CSCommonUtils;
using CsharpHttpHelper;
using FX_API.Factory;
using FX_API.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FX_API.Request
{
    public class FXCommonUploadRequest: FXBasicRequest
    {
        public delegate void HttpResponseHandler(string responseMsg, FXCreateRequestModel request);
        public HttpResponseHandler httpErrHandler;

        public override string url { get; set; }

        /// <summary>
        /// 返回创建新对象的纷享返回结果
        /// 如果发生异常则返回null，通过委托来处理，不需要额外处理
        /// </summary>
        /// <param name="object_data"></param>
        /// <param name="details"></param>
        /// <param name="triggerWorkFlow"></param>
        /// <returns></returns>
        public FXCreateResponseModel Upload(IObjectData object_data, object details = null, bool triggerWorkFlow = false)
        {
            FXCreateRequestModel requestModel;
            FXCreateResponseModel responseModel = null;

            url = object_data.dataObjectApiName.EndsWith("__c") ? FenxiangAPI.customizedCreateURL : FenxiangAPI.presetCreateURL;

            try
            {
                if (details == null)
                {
                    requestModel = UploadModelFactory.GetFXCreateRequestModel(object_data, triggerWorkFlow);
                }
                else
                {
                    requestModel = UploadModelFactory.GetFXCreateRequestModelWithDetails(object_data, details, triggerWorkFlow);
                }

                var response = SendRequest(requestModel);

                if (!response.IsSucess)
                {
                    httpErrHandler?.Invoke(response.Message, requestModel);
                    return null;
                }

                responseModel = JsonConvert.DeserializeObject<FXCreateResponseModel>(response.Message);
            }
            catch (Exception ex)
            {
                exceptionHandler?.Invoke(ex);
            }

            return responseModel;
        }
    }
}
